using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    public AudioSource m_AudioSourceNormal;
    public AudioSource m_AudioSourceBGM;
    public List<AudioClip> m_AudioClipArr;
    public bool MusicFlag
    {
        get { return m_MusicFlag; }
        set { m_MusicFlag = value; }
    }
    // public Dictionary<string, AudioClip> m_AudioClipMap;

    public static AudioManager Instance;

    public static void PlayClickItemAudio()
    {
        if (Instance)
            Instance.PlayAudioSource("Click_da");
    }

    public static void PlaySuccessAudio()
    {
        if (Instance)
            Instance.PlayAudioSource("Success_happy");
    }

    public static void PlayFailureAudio()
    {
        if (Instance)
            Instance.PlayAudioSource("Failure_beng");
    }
    public static void PlayBGMAudio()
    {
        if (Instance)
            Instance._PlayBGMAudio();
    }

    public void PlayAudioSource(string name)
    {
        AudioClip audioClip;
        if (m_AudioSourceMap.TryGetValue(name, out audioClip))
        {
            if (m_AudioSourceNormal.isPlaying)
            {
                m_AudioSourceNormal.Stop();
            }
            m_AudioSourceNormal.clip = audioClip;
            m_AudioSourceNormal.Play();
            float volume = name == "Click_da" ? 1f : 0.4f;
            m_AudioSourceNormal.volume = volume;
        }

    }

    public void SwitchMusic()
    {
        if (m_MusicFlag)
            StopBGMAudio();
        else
            PlayBGMAudio();
    }

    public void StopBGMAudio()
    {
        if (Instance)
            Instance._StopBGMAudio();
    }

    //=========================================公私分界线==================================================

    private Dictionary<string, AudioClip> m_AudioSourceMap = new Dictionary<string, AudioClip>();
    private bool m_MusicFlag = true;
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        Instance = this;

        for (int i = 0; i < m_AudioClipArr.Count; i++)
        {
            m_AudioSourceMap.Add(m_AudioClipArr[i].name, m_AudioClipArr[i]);
        }
    }

    private void _PlayBGMAudio()
    {
        StopBGMAudio();
        m_AudioSourceBGM.Play();
        m_AudioSourceBGM.loop = true;
        m_AudioSourceBGM.volume = 1f;
        m_MusicFlag = true;
    }

    private void _StopBGMAudio()
    {
        if (m_AudioSourceBGM.isPlaying)
        {
            m_AudioSourceBGM.Stop();
        }
        m_MusicFlag = false;
    }

}
